package cn.ibizlab.util.web;

import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class IPUtils {

    public static String getIpAddr(HttpServletRequest request) {

        if (request == null && RequestContextHolder.getRequestAttributes() != null && RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes )
            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request == null)
            return null;


        String ip = request.getHeader("x-forwarded-for");
        if (!ObjectUtils.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip) && ip.indexOf(",")!=-1 )
            ip = ip.split(",")[0];
        if (isEmpty(ip))
            ip = request.getHeader("Proxy-Client-IP");
        if (isEmpty(ip))
            ip = request.getHeader("WL-Proxy-Client-IP");
        if (isEmpty(ip))
            ip = request.getHeader("HTTP_CLIENT_IP");
        if (isEmpty(ip))
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        if (isEmpty(ip))
            ip = request.getHeader("X-Real-IP");
        if (isEmpty(ip))
            ip = request.getRemoteAddr();
        return ip;
    }

    private static boolean isEmpty(String value) {
        return ObjectUtils.isEmpty(value) ||  "unknown".equalsIgnoreCase(value);
    }

    private IPUtils() {

    }
}
